<template>
  <addEditBaseStudentView ref="addEditBaseStudentView"></addEditBaseStudentView>
  <el-dialog v-model="dialogFormVisible" :title="title" @close="closeDialog" width="80%">
    <el-form :inline="true" class="demo-form-inline" v-model="form">
      <el-form-item label="所在学年" :label-width="formLabelWidth" prop="classId">
        <el-select clearable v-model="form.schoolYear" autocomplete="off" placeholder="请选择所在学年" style="width:200px;">
          <el-option v-for="item in schoolYears" :key="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="考试名称" :label-width="formLabelWidth" prop="classId">
        <el-select clearable v-model="form.typeName" autocomplete="off" placeholder="请选择考试名称" style="width:200px;">
          <el-option v-for="item in types" :key="item.name" :value="item.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所在年级" :label-width="formLabelWidth" prop="gradeId">
        <el-select clearable v-model="form.gradeId" autocomplete="off" @change="filterGradeId" placeholder="请选择所在年级"
          style="width:200px;">
          <el-option v-for="gradeId in gradeIds" :key="gradeId" :value="gradeId"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-upload ref="upload" class="upload-demo" :limit="1" :on-exceed="handleExceed" :auto-upload="false"
      :file-list="fileList" :on-change="fileChange" :before-remove="handleRemove"
      accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
      <template #trigger>
        <el-button type="primary" plain>选择文件</el-button>
      </template>
      <el-button class="upload-btn" type="warning" @click="submitUpload" plain
        v-loading.fullscreen.lock="fullscreenLoading">智能分析</el-button>
      <el-button class="upload-btn" type="success" v-if="isResult" @click="submitData" plain
        v-loading.fullscreen.lock="fullscreenLoading">提交数据</el-button>
      <template #tip>
        <div class="el-upload__tip" style="color: red">
          选择正确模版的Excel文件，并且只能选择一个文件!
        </div>
        <div class="el-upload__tip" style="color: #409eff; cursor: pointer" v-if="templateUrl != ''">
          <el-link :href="templateUrl" type="success">点此下载模版文件</el-link>
        </div>
      </template>
    </el-upload>

    <div style="font-size: 18px" v-if="isResult">
      智能分析结果：
      <span v-if="differentCampusStudent.length == 0 &&
    differentClassStudent.length == 0 &&
    differentNameStudent.length == 0 &&
    differentGradeStudent.length == 0 &&
    errorData.length == 0 &&
    notExistStudent.length == 0
    ">全部数据通过分析，请点击提交数据按钮上传成绩。</span>
      <span v-else>以下数据存在问题</span>
    </div>
    <div>
      <div v-if="differentCampusStudent.length > 0">
        <div class="s-title">校区错误的学生</div>

        <el-table size="small" :data="differentCampusStudent" border :row-class-name="tableRowClassName">
          <el-table-column prop="index" label="序号" width="50">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="考试名称" width="170" />
        </el-table>
      </div>
      <div v-if="differentClassStudent.length > 0">
        <div class="s-title">班级错误的学生</div>
        <el-table size="small" :data="differentClassStudent" border :row-class-name="tableRowClassName">
          <el-table-column prop="index" label="序号" width="50">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="studentNumber" label="学号" width="100" />
          <el-table-column prop="clazzName" label="系统中的班号" width="100" />
          <el-table-column prop="notRightClassName" label="Excel中的班号" width="100" />
          <el-table-column prop="notRightClassName" label="操作" width="100">
            <template #default="scope">
              <el-button size="small" type="success"
                @click="oneKeyChangeClass(scope.$index, scope.row)">一键转班</el-button>
            </template>
          </el-table-column>

          <el-table-column prop="name" label="提示">
            <template #default="scope">
              班级信息不符合，修改Excel中的第{{ scope.row.line }}行班级为{{
    scope.row.clazzName
  }}，或直接操作转班。
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="differentNameStudent.length > 0">
        <div class="s-title">姓名学号不匹配的学生</div>
        <el-table size="small" :data="differentNameStudent" border :row-class-name="tableRowClassName">
          <el-table-column prop="index" label="序号" width="50">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="系统中的姓名" width="100" />
          <el-table-column prop="notRightName" label="Excel中的姓名" width="100" />
          <el-table-column prop="studentNumber" label="学号" width="100" />
          <el-table-column prop="notRightClassName" label="操作" width="100">
            <template #default="scope">
              <el-button size="small" type="success"
                @click="oneKeyChangeStudentName(scope.$index, scope.row)">一键改名</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="提示">
            <template #default="scope">
              手动修改Excel中的第{{
    scope.row.line
  }}行学生姓名，一键修改系统中的学生姓名
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="differentGradeStudent.length > 0">
        <div class="s-title">年级不匹配的学生</div>
        <el-table size="default" :data="differentGradeStudent" :row-class-name="tableRowClassName">
          <el-table-column prop="index" label="序号" width="50">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="studentNumber" label="学号" width="100" />
          <el-table-column prop="clazzName" label="系统中的年级" width="100" />
          <el-table-column prop="notRightClassName" label="Excel中的年级" width="100" />
          <el-table-column prop="name" label="提示">
            <template #default="scope">
              年级信息不符合，修改Excel中的第{{ scope.row.line }}行年级为{{
    scope.row.clazzName
  }}。或在【学生管理】-【学生信息】中搜索并编辑该学生年级，获取新的学号后填充到Excel中的第{{
      scope.row.line
    }}行学生学号里。
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="errorData.length > 0">
        <div class="s-title">错误的分数</div>
        <el-table size="small" :data="errorData" border :row-class-name="tableRowClassName">
          <el-table-column prop="index" label="序号" width="50">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="考试名称" width="170" />
        </el-table>
      </div>
      <div v-if="notExistStudent.length > 0">
        <div class="s-title">系统中不存在的学生</div>
        <el-table size="small" :data="notExistStudent" border :row-class-name="tableRowClassName">
          <el-table-column prop="index" label="序号" width="50">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="studentNumber" label="学号" width="100" />
          <el-table-column prop="notRightClassName" label="操作" width="100">
            <template #default="scope">
              <el-button size="small" type="success" @click="registerStudent(scope.$index, scope.row)">快捷注册</el-button>
            </template>
          </el-table-column> <el-table-column prop="name" label="提示">
            <template #default="scope">
              修改Excel中的第{{ scope.row.line }}行学生学号为正确的学号，若学生不存在可快捷注册、查询学号后修改Excel
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { ref } from "vue";
import { httpService } from "@/utils/httpService";
import { ElMessage, ElForm, ElLoading, ElMessageBox } from "element-plus";
import addEditBaseStudentView from "@/components/baseInfo/addEditBaseStudent.vue";

export default {
  name: "AddExcelFile",
  components: { ElForm, ElMessage, ElLoading, ElMessageBox, addEditBaseStudentView },
  data() {
    return {
      dialogFormVisible: ref(false),
      fullscreenLoading: false,
      // formLabelWidth: "80px",
      title: "",
      isResult: false,
      differentCampusStudent: [],
      differentClassStudent: [],
      differentNameStudent: [],
      differentGradeStudent: [],
      errorData: [],
      notExistStudent: [],
      form: {
        gradeId: "",
        schoolYear: "",
        typeName: "",
      },
      gradeIds: [],
      types: [],

      uploadApiUrl: "",
      schoolYears: [],
      fileList: [],
      templateUrl: "",
    };
  },
  mounted() {
    console.log(111, this.types);
  },
  methods: {
    registerStudent(index, row) {
      this.$refs.addEditBaseStudentView.title = "注册学生";
      this.$refs.addEditBaseStudentView.getGradeIds();
      this.$refs.addEditBaseStudentView.getBaseClassInfoList();
      this.$refs.addEditBaseStudentView.addBaseStudentForm.name = row.name;
      this.$refs.addEditBaseStudentView.addBaseStudentForm.gradeId = this.form.gradeId;
      this.$refs.addEditBaseStudentView.dialogFormVisible = true;
    },
    oneKeyChangeClass(index, row) {
      ElMessageBox.confirm(
        "确定要将系统中学生【" +
        row.name +
        "-" +
        row.studentNumber +
        "】的班级【" +
        row.clazzName +
        "班】转为Excel中的班级【" +
        row.notRightClassName +
        "班】吗？",
        "提醒",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          let params = new FormData();
          params.append("id", row.id);
          params.append("classId", row.notRightClassName);
          params.append("gradeId", row.gradeId);
          httpService("/javaApi/baseStudent/edit", params, "post").then(
            (data) => {
              if (data.code == 200) {
                this.differentClassStudent.splice(index, 1);
                ElMessage.success("转班成功");
              } else {
                ElMessage.error("转班失败，请重试！");
              }
            }
          );
        })
        .catch(() => { });
    },
    oneKeyChangeStudentName(index, row) {
      ElMessageBox.confirm(
        "确定要将系统中学号为【" +
        row.studentNumber + "】的学生【" +
        row.name + "】修改为Excel中的姓名【" +
        row.notRightName +
        "】吗？",
        "提醒",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          let params = new FormData();
          params.append("id", row.id);
          params.append("gradeId", row.gradeId);
          params.append("name", row.notRightName);
          httpService("/javaApi/baseStudent/edit", params, "post").then(
            (data) => {
              if (data.code == 200) {
                this.differentNameStudent.splice(index, 1);
                ElMessage.success("修改成功");
              } else {
                ElMessage.error("修改失败");
              }
            }
          );
        })
        .catch(() => { });
    },
    closeDialog() {
      this.clear();
    },
    cancel() {
      this.dialogFormVisible = false;
      this.clear();
    },
    clear() {
      this.dialogFormVisible = false;
      this.$refs.upload.clearFiles();
      this.fileList = [];
      this.isResult = false;
      this.differentCampusStudent = [];
      this.differentClassStudent = [];
      this.differentNameStudent = [];
      this.differentGradeStudent = [];
      this.errorData = [];
      this.notExistStudent = [];
    },
    fileChange(file, fileList) {
      this.fileList = fileList;
    },
    handleRemove() {
      this.$refs.upload.clearFiles();
      this.fileList = [];
    },
    handleExceed(files) {
      this.$refs.upload.clearFiles();
      this.fileList = [];
      this.$refs.upload.handleStart(files[0]);
    },
    submitData() {
      this.fullscreenLoading = true;
      let params = new FormData();
      httpService(
        "/javaApi/baseAchievement/importRealExcel",
        params,
        "post"
      ).then((data) => {
        this.fullscreenLoading = false;
        if (data.code == 200) {
          ElMessage.success(data.object);
          this.clear();
          //刷新父组件的数据
          this.$parent.reloadData();
        } else {
          ElMessage.error(data.message);
        }
      });
    },
    submitUpload() {
      if (this.form.schoolYear == "") {
        ElMessage.error("请选择学年后上传");
        return;
      }
      if (this.form.typeName == "") {
        ElMessage.error("请选择考试名称后上传");
        return;
      }
      if (this.form.gradeId == "") {
        ElMessage.error("请选择年级后上传");
        return;
      }
      let params = new FormData(); //创建一个form对象,必须是form对象否则后端接受不到数据
      if (this.fileList.length > 0) {
        if (this.fileList[0].raw) {
          this.fullscreenLoading = true;
          params.append("file", this.fileList[0].raw);
          params.append("gradeId", this.form.gradeId);
          params.append("name", this.form.typeName);
          params.append("schoolYear", this.form.schoolYear);

          let config = { "Content-Type": "multipart/form-data" };
          httpService(this.uploadApiUrl, params, "post", config).then(
            (data) => {
              this.fullscreenLoading = false;
              if (data.code == 200) {
                this.isResult = true;
                console.log(data.object);
                this.differentCampusStudent =
                  data.object.differentCampusStudent;
                this.differentClassStudent = data.object.differentClassStudent;
                this.differentNameStudent = data.object.differentNameStudent;
                this.differentGradeStudent = data.object.differentGradeStudent;
                this.errorData = data.object.errorData;
                this.notExistStudent = data.object.notExistStudent;
              } else {
                ElMessage.error(data.message);
              }
            }
          );
        }
      } else {
        ElMessage.error("请选择文件");
      }
    },
  },
};
</script>
<style scoped>
.s-title {
  padding: 20px 0px;
  color: black;
}

.el-dialog__header {
  padding: var(--el-dialog-padding-primary);
  padding-bottom: 10px;
  border-bottom: 1px solid #dedede;
}

.upload-demo {
  padding: 20px;
  border: 1px solid #dedede;
  margin-bottom: 20px;
}

.upload-btn {
  margin-left: 10px;
}

.el-upload__tip {
  padding-top: 10px;
  padding-bottom: 10px;
}
</style>